<?php 
class AnswersController extends AppController {
	
	public $uses = array('Answer', 'Question');
	
	public function beforeFilter() {
		parent::beforeFilter();
	}
	
	public function DialogAddAnswer($question_id){
		$this->set('question_id', $question_id);
	}
	
	public function AddAnswerByJson(){
		$query = $this->request->query;
		$data['Answer']['question_id'] = $query['question_id'];
		$data['Answer']['content'] = $query['content'];
		if ($query['correct'] == 'true' || $query['correct'] == 'TRUE') {
			$data['Answer']['correct'] = true;
		}else{
			$data['Answer']['correct'] = false;
		}
		
		$create = $this->CreateAnswer($data);
		$answerId=$this->Answer->getLastInsertID();
		if ($create) {
			$this->set('status', true);
			$this->set('message', 'Add answer success');
		}else {
			$this->set('status', false);
			$this->set('message', 'Please enter input');
		}
		$this->set('answerId', $answerId);
		$this->set('_serialize', array('status', 'message', 'answerId'));
	}
	
	private function CreateAnswer($data){
		$this->Answer->set($data);
		if ($this->Answer->AddAnswerValidate()) {
			$data['Answer']['created'] = date('Y-m-d H:i:s', time());
			$data['Answer']['modified'] = date('Y-m-d H:i:s', time());
			$this->Answer->save($data, false);
			return true;
		}
		return false;
	}
	
	public function ShowByQuestion($question_id){
		$answers = $this->Answer->find('all', array(
					'fields' => array(
						'Answer.id',
					),
					'conditions' => array('Answer.question_id' => $question_id),
					'recursive' => 0
				));
		$this->set('answers', $answers);
		$this->set('question_id', $question_id);
	}
	
	public function Show($answer_id, $position = null){
		$answer = $this->Answer->find('first', array(
					'fields' => array(
						'Answer.id',
						'Answer.correct',
						'Answer.content',
						'Answer.question_id'
					),
					'conditions' => array('Answer.id' => $answer_id),
					'recursive' => 0
				));
		if ($position == null) {
			$count= $this->Answer->find('count', array('conditions' => array('Answer.question_id' => $answer['Answer']['question_id'])));
			if (!empty($count)) {
				$position = $count;
			}else {
				$position = 1;
			}
		}
		$this->set('answer', $answer);
		$this->set('position', $position);
	}
	
	public function edit($id){
		$answer = $this->Answer->find('first', array('conditions'=>array('id'=>$id)));
		$this->set('answer', $answer);
		if($this->request->query){
			$this->Answer->save($this->request->query);
			$this->redirect(SITE_URL."questions/ShowQuestion/".$answer['Answer']['question_id']);
		}
	}

	public function delete($id){
		$answer = $this->Answer->find('first', array('conditions'=>array('id'=>$id)));
		if($this->Answer->delete($id)){
			$this->redirect(SITE_URL."questions/ShowQuestion/".$answer['Answer']['question_id']);
		}
	}
}